package com.richard.library.basic.util;

import android.text.TextUtils;

/**
 * @author: Richard
 * @createDate: 2024/10/22 17:48
 * @version: 1.0
 * @description: url 工具类
 */
public final class URLUtil {

    private URLUtil() {
    }

    /**
     * 获取指定url中的某个参数
     *
     * @param url  链接
     * @param name 指定获取的参数名
     * @return 返货参数名的value
     */
    public static String getParamByUrl(String url, String name) {
        if (url != null && !url.isEmpty()) {
            int index = url.indexOf("?");
            String temp = (index >= 0 ? url.substring(index + 1) : url);
            String[] keyValue = temp.split("&");
            String destPrefix = name + "=";
            for (String str : keyValue) {
                if (str.indexOf(destPrefix) == 0) {
                    return str.substring(destPrefix.length());
                }
            }
        }
        return null;
    }

    /**
     * 补全URL
     */
    public static String completion(String host, String relativeUrl) {
        if(TextUtils.isEmpty(host)){
            return relativeUrl;
        }

        if(TextUtils.isEmpty(relativeUrl)){
            return host;
        }

        if (relativeUrl.startsWith("http")) {
            return relativeUrl;
        }

        if (host.endsWith("/") && relativeUrl.startsWith("/")) {
            return host.concat(relativeUrl.substring(1));
        }

        if (!host.endsWith("/") && !relativeUrl.startsWith("/")) {
            return host.concat("/").concat(relativeUrl);
        }

        return host.concat(relativeUrl);
    }

}
